<template>
  <div class="neuTableExcel">
    <el-tooltip effect="dark" content="表格导出Excel" placement="top">
      <svg class="iconExcel" aria-hidden="true" @click="init()">
        <use xlink:href="#com-icon-Microsoft-Excel"></use>
      </svg>
    </el-tooltip>
    <el-drawer
      title="导出设置"
      :visible.sync="drawer"
      direction="rtl"
      :wrapperClosable="false"
      :before-close="handleClose"
      :append-to-body="true"
      size="250px"
    >
      <div class="exportContent">
        <div class="operation">
          <el-button size="medium" @click="exportCurrent()">当前页</el-button>
          <el-button size="medium" type="primary" @click="exportAll()"
            >全部</el-button
          >
        </div>
        <el-divider><i>导出列选择</i></el-divider>
        <div class="checkedColumns">
          <el-checkbox
            :indeterminate="isIndeterminate"
            v-model="checkAll"
            @change="handleCheckAllChange"
            >全选</el-checkbox
          >
        </div>
        <el-scrollbar>
          <el-checkbox-group
            v-model="checkedColumns"
            @change="handleCheckedColumnChange"
          >
            <el-checkbox
              v-for="column in allColumns"
              :label="column.prop"
              :key="column.prop"
              border
              >{{ column.label }}
            </el-checkbox>
          </el-checkbox-group>
        </el-scrollbar>
      </div>
    </el-drawer>
  </div>
</template>
<script>
import _ from "lodash";

export default {
  props: {
    //表格所有列
    columns: {
      type: Array,
      default: () => {
        return [];
      }
    },
    //当前页数据
    currentData: {
      type: Array,
      default: () => {
        return [];
      }
    },
    //Excel导出的参数
    exportParams: {
      type: Object,
      default: () => {
        return {};
      }
    }
  },
  data() {
    return {
      //table
      table: {},
      //是否全选
      checkAll: false,
      //所有可以进行导出的列
      allColumns: [],
      //选中的列
      checkedColumns: [],
      //全选的样式
      isIndeterminate: true,
      //全选的结果
      checkedAllColumns: [],
      //导出的数据
      excelData: [],
      //导出的表头
      tHeader: [],
      //数据的字段
      filterVal: [],
      //图标变大
      large: false,
      //打开抽屉
      drawer: false,
      //格式化方法
      formatter: {},
      //二级代码字段
      dicts: {},
      //Excel列宽
      excelColumnWidth: []
    };
  },
  computed: {
    fileName(fileName = "表格数据") {
      fileName = this.exportParams.fileName;
      return fileName;
    },
    exportApi() {
      return this.exportParams.exportApi;
    }
  },
  methods: {
    init: function() {
      this.drawer = true;
      this.allColumns = [];
      this.checkedColumns = [];
      this.tHeader = [];
      this.filterVal = [];
      this.excelData = [];
      this.checkAll = true;
      this.isIndeterminate = false;
      for (let item of this.columns) {
        const prop = item.prop;
        const label = item.label;
        if (prop && label && label != "操作") {
          const formatter = item.formatter;
          const dict = item.dict;
          this.allColumns.push({ prop: prop, label: label });
          this.checkedColumns.push(prop);
          this.checkedAllColumns.push(prop);
          this.formatter[prop] = formatter;
          if (dict) {
            this.dicts[prop] = dict;
          }
          const width = item.minWidth ? item.minWidth : 100;
          this.excelColumnWidth.push(width);
        }
      }
    },
    handleCheckAllChange(val) {
      this.checkedColumns = val ? this.checkedAllColumns : [];
      this.checkAll = val;
      this.isIndeterminate = false;
    },
    handleCheckedColumnChange(value) {
      let checkedCount = value.length;
      this.checkAll = checkedCount === this.allColumns.length;
      this.isIndeterminate =
        checkedCount > 0 && checkedCount < this.allColumns.length;
    },
    handleClose(done) {
      this.drawer = false;
    },
    checkSelectedColumns(rowData) {
      let exportRowData = {};
      let checkedColumns = this.checkedColumns;
      for (let key in rowData) {
        if (checkedColumns.includes(key)) {
          exportRowData[key] = rowData[key];
        }
      }
      return exportRowData;
    },
    setHeader() {
      this.tHeader = [];
      this.filterVal = [];
      for (let columns of this.allColumns) {
        if (this.checkedColumns.includes(columns.prop)) {
          this.tHeader.push(columns.label);
          this.filterVal.push(columns.prop);
        }
      }
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => v[j]));
    },
    formatterExportData(data) {
      for (let rowData of data) {
        for (let prop in rowData) {
          const formatter = this.formatter[prop];
          if (formatter) {
            rowData[prop] = formatter("scope", rowData[prop]);
          }
        }
      }
      return data;
    },
    async exportAll() {
      Utils.Tools.store.showLoading();
      this.setHeader();
      let { api, url } = this.exportApi;
      const params = {
        exportFlag: true,
        excelFilename: this.fileName,
        excelHeaderList: this.tHeader,
        excelColumnList: this.filterVal,
        dicts: this.dicts,
        excelColumnWidth: this.excelColumnWidth,
        ...this.exportParams.searchParams,
        excelAllFlag: true
      };
      let config = {
        method: "EXCEL_DOWNLOAD",
        blobType:
          "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8",
        fileName: this.fileName
      };
      const result = await api[url](params, null, config);
      Utils.Tools.store.hideLoading();
      this.handleClose();
    },
    exportCurrent() {
      this.setHeader();
      const currentData = _.cloneDeep(this.currentData);
      this.excelData = this.formatterExportData(currentData);
      this.saveExcel();
    },
    saveExcel() {
      try {
        const { export_json_to_excel } = require("../../utils/ExportToExcel");
        const tHeader = this.tHeader;
        const filterVal = this.filterVal;
        const list = this.excelData;
        const data = this.formatJson(filterVal, list);
        const excelName = this.fileName;
        export_json_to_excel(tHeader, data, excelName);
      } catch (error) {
        console.log(error);
      } finally {
        this.handleClose();
      }
    }
  }
};
</script>
<style scoped lang="scss">
.neuTableExcel {
  .iconExcel {
    margin-right: 5px;
    height: 25px;
    width: 25px;
    cursor: pointer;
  }
  .iconExcelLarge {
    position: relative;
    height: 35px;
    width: 35px;
  }
}
.exportContent {
  height: 100%;
  padding: 5px 10px;
  .operation {
    width: 100%;
    display: flex;
    flex-direction: row;
    justify-content: space-around;
    align-items: center;
    margin: 10px 0 0 0;
    button {
      width: 100%;
    }
  }
  .i {
    color: #303133;
  }
  .el-scrollbar {
    height: calc(100% - 150px);
  }
  ::v-deep .el-scrollbar__wrap {
    overflow-x: hidden;
    height: calc(100%);
  }
  .checkedColumns {
    margin-bottom: 10px;
  }
}
::v-deep .el-drawer__header {
  -webkit-box-align: center;
  -ms-flex-align: center;
  align-items: center;
  color: #72767b;
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  margin-bottom: 5px;
  padding: 23px;
  padding-bottom: 0;
}
::v-deep .el-checkbox {
  color: #606266;
  font-weight: 500;
  width: 85%;
  font-size: 14px;
  position: relative;
  cursor: pointer;
  display: inline-block;
  white-space: nowrap;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
  margin: 10px 10px 0 0;

  &:first-child {
    margin-left: 10px;
  }
}
::v-deep .el-checkbox.is-bordered {
  padding: 9px 20px 9px 10px;
  border-radius: 4px;
  border: 1px solid #dcdfe6;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  line-height: normal;
  height: 40px;
}
::v-deep .el-checkbox.is-bordered.is-checked {
  border-color: #1b65b9;
}
::v-deep .el-divider--horizontal {
  display: block;
  height: 1px;
  width: 100%;
  margin: 22px 0 10px 0;
}
</style>
